<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\PersonalHistoryStoreRequest;
use App\Http\Requests\PersonalHistoryUpdateRequest;
use App\Models\PersonalHistory;
use App\Project\Filters\PersonalHistoryFilter;
use App\Project\Transform;
use App\Transformers\PersonalHistoryTransformer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class PersonalHistoryController extends ApiController
{
    /**
     * 个人史提交
     * @param \App\Http\Requests\PersonalHistoryStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(PersonalHistoryStoreRequest $request)
    {
        $input = (new PersonalHistoryFilter($request))->input();

        $result = PersonalHistory::updateOrCreate( ['record_id' => $input['record_id']], $input );

        return $this->response( ['id' => $result->id] );
    }

    /**
     * 个人史信息更新页面的信息获取
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = null;
        $id   = $request->get( 'id' );

        if ($id > 0) {
            $data = PersonalHistory::findOrFail( $id );
        } elseif ($record_id = $request->get( 'record_id' )) {
            $data = PersonalHistory::where( ['record_id' => $record_id] )->first();
        } else {
            abort( 400, '缺失个人史ID，或者病历ID' );
        }

        if (empty( $data )) {
            throw (new ModelNotFoundException())->setModel( PersonalHistory::class );
        }

        return $this->item( $data, new PersonalHistoryTransformer() );
    }

    /**
     * 个人史更新动作
     * @param \App\Http\Requests\PersonalHistoryUpdateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(PersonalHistoryUpdateRequest $request)
    {
        $where = [];

        if ($id = $request->input( 'id' )) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $request->input( 'record_id' );
        }

        $input = (new PersonalHistoryFilter($request))->except( ['id', 'record_id'] );

        $input = (new Transform())->setArray( $input )->convertArrayToJson(
            ['smoke', 'drink']
        )->get();

        $result = PersonalHistory::where( $where )->update( $input );

        return $this->responseForUpdate( $result );
    }


}
